#include <stdio.h>
#include <unistd.h>

void print_usage(char* prgname)
{
	printf("Show how 'getopt' works\n");
	printf("Usage: %s [-a 1] [-b 2] [-c 3] arg1 arg2\n", prgname);

	printf("input unorder, eg: \n");
	printf("\t%s arg1 -c2 arg2 -b 3 -a\n", prgname);
	printf("\t%s arg1 -c arg2 -b 3\n", prgname);
}

int main(int argc, char** argv)
{
	if (argc < 3)
	{
		print_usage(argv[0]);
		return 0;
	}

	int arg_a = 0;
	char* arg_b = "";
	char* arg_c = "";

	int c;
	// 两个冒号表示可以不带参数，也可以带参数（但参数与选项间不能有空格）
	while ( (c = getopt(argc, argv, "ab:c::")) != -1)
	{
		switch (c)
		{
		case 'a':
			arg_a = 1;
			break;
		case 'b':
			arg_b = optarg;
			break;
		case 'c':
			arg_c = optarg ? optarg : "";
			break;
		default:
			print_usage(argv[0]);
			return 0;
			break;
		}
	}

	char* arg1 = argv[optind];
	char* arg2 = argv[optind + 1];

	printf("parsed : %s -b %s -c%s %s %s\n", arg_a ? "-a" : "", arg_b, arg_c, arg1, arg2);


	printf("reorder: ");
	// getopt will reorder command line
	for (int i = 0; i < argc; i++)
		printf("%s ", argv[i]);

	printf("\n");

	return 0;
}
